import java.io.*;
import java.util.*;

public class ScoreManagementSystem {
    private List<Student> students = new ArrayList<>();
    private List<Course> courses = new ArrayList<>();
    private List<Score> scores = new ArrayList<>();

    // 关键：获取系统桌面绝对路径（适配Windows、Mac、Linux）
    private static final String USER_HOME = System.getProperty("user.home");
    private static final String DESKTOP = System.getProperty("os.name").toLowerCase().contains("win")
            ? "Desktop" : "Desktop"; // Windows和Mac/Linux桌面目录名一致
    private static final String DESKTOP_PATH = USER_HOME + File.separator + DESKTOP + File.separator;

    // CSV文件路径（桌面目录下）
    private static final String S_CSV = DESKTOP_PATH + "students.csv";
    private static final String C_CSV = DESKTOP_PATH + "courses.csv";
    private static final String SC_CSV = DESKTOP_PATH + "scores.csv";

    public ScoreManagementSystem() {
        loadData();
    }

    // 添加学生、课程（不变）
    public void addStudent(Student s) { students.add(s); }
    public void addCourse(Course c) { courses.add(c); }

    // 添加成绩（带重复校验）
    public boolean addScore(Score s) {
        // 校验学生+课程组合是否已存在成绩
        for (Score exist : scores) {
            if (exist.getStudent().getStudentId().equals(s.getStudent().getStudentId())
                    && exist.getCourse().getCourseId().equals(s.getCourse().getCourseId())) {
                return false; // 重复，添加失败
            }
        }
        scores.add(s);
        return true; // 添加成功
    }

    // 按课程查询成绩
    public List<Score> getScoresByCourse(String cid) {
        List<Score> res = new ArrayList<>();
        for (Score s : scores) {
            if (s.getCourse().getCourseId().equals(cid)) res.add(s);
        }
        return res;
    }

    // 计算GPA
    public double calcGPA(String sid) {
        double totalP = 0, totalC = 0;
        for (Score s : scores) {
            if (s.getStudent().getStudentId().equals(sid)) {
                double credit = s.getCourse().getCredit();
                totalC += credit;
                totalP += (s.getScore() >= 90 ? 4 : s.getScore() >= 80 ? 3 :
                        s.getScore() >= 70 ? 2 : s.getScore() >= 60 ? 1 : 0) * credit;
            }
        }
        return totalC > 0 ? totalP / totalC : 0;
    }

    // 保存数据到桌面CSV
    public void saveData() {
        try (BufferedWriter sw = new BufferedWriter(new FileWriter(S_CSV));
             BufferedWriter cw = new BufferedWriter(new FileWriter(C_CSV));
             BufferedWriter scw = new BufferedWriter(new FileWriter(SC_CSV))) {

            // 保存学生
            sw.write("学号,姓名,班级");
            for (Student s : students) {
                sw.write("\n" + s.getStudentId() + "," + esc(s.getName()) + "," + esc(s.getClassName()));
            }

            // 保存课程
            cw.write("课程编号,课程名称,学分");
            for (Course c : courses) {
                cw.write("\n" + c.getCourseId() + "," + esc(c.getName()) + "," + c.getCredit());
            }

            // 保存成绩
            scw.write("学生学号,课程编号,分数");
            for (Score s : scores) {
                scw.write("\n" + s.getStudent().getStudentId() + "," + s.getCourse().getCourseId() + "," + s.getScore());
            }

            System.out.println("✅ 数据已保存到桌面！路径：" + DESKTOP_PATH);
        } catch (IOException e) {
            System.out.println("❌ 保存失败：" + e.getMessage());
        }
    }

    // 加载桌面CSV数据
    private void loadData() {
        loadStudents();
        loadCourses();
        loadScores();
    }

    private void loadStudents() {
        try (BufferedReader br = new BufferedReader(new FileReader(S_CSV))) {
            br.readLine(); // 跳过表头
            String line;
            while ((line = br.readLine()) != null) {
                String[] parts = parse(line);
                if (parts.length == 3) students.add(new Student(parts[0], parts[1], parts[2]));
            }
            System.out.println("✅ 学生数据加载成功");
        } catch (FileNotFoundException e) {
            System.out.println("ℹ️  未找到学生CSV文件（首次运行）");
        } catch (Exception e) {
            System.out.println("❌ 学生数据加载失败：" + e.getMessage());
        }
    }

    private void loadCourses() {
        try (BufferedReader br = new BufferedReader(new FileReader(C_CSV))) {
            br.readLine();
            String line;
            while ((line = br.readLine()) != null) {
                String[] parts = parse(line);
                if (parts.length == 3) courses.add(new Course(parts[0], parts[1], Double.parseDouble(parts[2])));
            }
            System.out.println("✅ 课程数据加载成功");
        } catch (FileNotFoundException e) {
            System.out.println("ℹ️  未找到课程CSV文件（首次运行）");
        } catch (Exception e) {
            System.out.println("❌ 课程数据加载失败：" + e.getMessage());
        }
    }

    private void loadScores() {
        try (BufferedReader br = new BufferedReader(new FileReader(SC_CSV))) {
            br.readLine();
            String line;
            while ((line = br.readLine()) != null) {
                String[] parts = parse(line);
                if (parts.length == 3) {
                    Student s = students.stream()
                            .filter(st -> st.getStudentId().equals(parts[0]))
                            .findFirst().orElse(null);
                    Course c = courses.stream()
                            .filter(co -> co.getCourseId().equals(parts[1]))
                            .findFirst().orElse(null);
                    if (s != null && c != null) {
                        scores.add(new Score(s, c, Double.parseDouble(parts[2])));
                    }
                }
            }
            System.out.println("✅ 成绩数据加载成功");
        } catch (FileNotFoundException e) {
            System.out.println("ℹ️  未找到成绩CSV文件（首次运行）");
        } catch (Exception e) {
            System.out.println("❌ 成绩数据加载失败：" + e.getMessage());
        }
    }

    // CSV特殊字符处理（逗号、引号）
    private String esc(String s) {
        return s.contains(",") || s.contains("\"") ? "\"" + s.replace("\"", "\"\"") + "\"" : s;
    }

    // 解析CSV行（支持带引号的字段）
    private String[] parse(String line) {
        List<String> parts = new ArrayList<>();
        StringBuilder sb = new StringBuilder();
        boolean inQuotes = false;
        for (char c : line.toCharArray()) {
            if (c == '"') inQuotes = !inQuotes;
            else if (c == ',' && !inQuotes) {
                parts.add(sb.toString());
                sb.setLength(0);
            } else sb.append(c);
        }
        parts.add(sb.toString());
        return parts.toArray(new String[0]);
    }

    // Getter方法
    public List<Student> getStudents() { return students; }
    public List<Course> getCourses() { return courses; }
}